package com.honey.feature.io;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

@Deprecated
public class ReverseReadLine {
	private final int BUFFER_SIZE=256 ;
	
	private RandomAccessFile randomAccessFile = null;
	
	private long _position = 0 ;
	
	private final long _length ;
	
	private ByteBuffer buffer = null;
	
	
	FileChannel channel = null;
	public ReverseReadLine( File target ) throws Exception{
		this.randomAccessFile = new RandomAccessFile(target,"r");
		this._length = randomAccessFile.length();
		this.reset();
		
		//channel = randomAccessFile.getChannel() ;
	}
	
	public void reset(){
		this._position = _length;
	}
	
	/**
	 * 读取文件的最后一行
	 * @param target
	 * @param charset
	 * @return
	 * @throws IOException
	 */
	public String readPreviousLine(String charset) throws IOException {
		String answer = null;
		int legth =0;
		byte b =0;
		while (_position > 0) {
			_position --; 
			randomAccessFile.seek(_position);
			b = randomAccessFile.readByte();
			if ( b == 10){// \n
				break;
			}else if(  b == 13){ // \r
				continue;
			}else{
				legth++;
			}
		}
		if(_position > 0 || legth > 0){
			byte[] bytes = new byte[legth];
			if(_position == 0 )randomAccessFile.seek(0);
			randomAccessFile.read(bytes);
			answer = new String(bytes,0,legth,charset);
		}
		return answer ;
	}
	
	
	public String readPreviousLine2(String charset) throws Exception {
		StringBuilder answer = new StringBuilder();
		int legth =0;
		byte b =0;
		while (_position >= 0) {
			if( _position == 0 ){
				if(!fillBufffer() )return null;
			}
			_position--; 
			b = array[(int)_position];
			if ( b == 10){// \n
				break;
			}else if(  b == 13){ // \r
				continue;
			}else{
				legth++;
				answer.insert(0,(char)b);
			}
		}
		System.out.println(answer);
		return answer.toString() ;
	}
	
	int fill =1 ;
	byte[] array = null;
	private boolean fillBufffer() throws Exception{
		boolean answer = true ;
		long  begin = _length - BUFFER_SIZE * fill;
		if(begin <= 0){
			int size = (int)(_length - BUFFER_SIZE * (fill-1));
			if( size <= 0 ){
				answer = false;
			}else{
				buffer = ByteBuffer.allocate(size);
				begin = 0;
			}
		}else if(buffer == null ){
			buffer = ByteBuffer.allocate(BUFFER_SIZE);
		}
		if( answer ){
			buffer.clear();
			channel.position(begin);
			_position = channel.read(buffer);
			buffer.flip();
			array  = buffer.array();

			
			fill++;
		}
		return answer ;
	}
}
